/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

// Network topology
//
//        n0     n1
//        |      |
//       ----------
//       | Switch |
//       ----------
//        |      |
//        n2     n3
//
//
// - CBR/UDP flows from n0 to n1 and from n3 to n0
// - DropTail queues
// - Tracing of queues and packet receptions to file "openflow-switch.tr"
// - If order of adding nodes and netdevices is kept:
//      n0 = 00:00:00;00:00:01, n1 = 00:00:00:00:00:03, n3 = 00:00:00:00:00:07
//	and port number corresponds to node number, so port 0 is connected to n0, for example.

#include <iostream>
#include <fstream>
#include "ns3/point-to-point-module.h"
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
#include "ns3/applications-module.h"
#include "ns3/openflow-module.h"
#include "ns3/log.h"
#include "ns3/v4ping.h"


#include "ns3/flow-monitor.h"
#include "ns3/flow-monitor-module.h"


#include "DBAccess.h"
using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("OpenFlowCsmaSwitchExample");

bool verbose = false;
bool use_drop = false;
ns3::Time timeout = ns3::Seconds (0);

bool
SetVerbose (std::string value)
{
    verbose = true;
    return true;
}

bool
SetDrop (std::string value)
{
    use_drop = true;
    return true;
}

bool
SetTimeout (std::string value)
{
    try {
        timeout = ns3::Seconds (atof (value.c_str ()));
        return true;
    }
    catch (...) {
        return false;
    }
    return false;
}

const int nTerminalCount = 100;
const int nSwitchcount = 50;


double dTotalRunTime = 0.03;
double dStartTime = 0.0;
double dInterValWndTime = 0.01;
DBAccess gdb("SDN.db");

void DetectThrouthput( NodeContainer& terminals)
{
    // Create a BulkSendApplication and install it on node 0
    uint16_t port = 9;  // well-known echo port number
    uint32_t maxBytes = 0;
    BulkSendHelper source ("ns3::TcpSocketFactory",
                           Address (InetSocketAddress (Ipv4Address ("100.100.100.2"), port)));
    // Set the amount of data to send in bytes.  Zero is unlimited.
    source.SetAttribute ("MaxBytes", UintegerValue (maxBytes));
    // Set the segment size
    source.SetAttribute ("SendSize", UintegerValue (1000));
    ApplicationContainer sourceApps = source.Install (terminals.Get (0));
    sourceApps.Start (Seconds (dStartTime));
    sourceApps.Stop (Seconds (dStartTime + dTotalRunTime));

    // Create a PacketSinkApplication and install it on node 1
    PacketSinkHelper sink ("ns3::TcpSocketFactory",
                           InetSocketAddress (Ipv4Address::GetAny (), port));
    ApplicationContainer sinkApps = sink.Install (terminals.Get (1));
    sinkApps.Start (Seconds (dStartTime));
    sinkApps.Stop (Seconds (dStartTime + dTotalRunTime));

    // Run the simulation
    Simulator::Stop (Seconds (dStartTime + dTotalRunTime));
    Simulator::Run ();
    Simulator::Destroy ();

    Ptr<PacketSink> sink1 = DynamicCast<PacketSink> (sinkApps.Get (0));
    std::cout << "Total Bytes Received: " << sink1->GetTotalRx () << std::endl;
    std::cout << "Throughput: " << sink1->GetTotalRx ()/dTotalRunTime/1024/1024 << "MBps" << std::endl;
}

static void
PingRtt (std::string context, Time rtt)
{
    std::cout << context << " " << rtt << std::endl;
}

void
DetectRTT( NodeContainer& terminals)
{
    V4PingHelper ping (Ipv4Address ("100.100.100.2"));
    ping.SetAttribute ("Verbose", BooleanValue (true));
    ApplicationContainer p = ping.Install (terminals.Get (0));

    p.Start (Seconds (0));
    p.Stop (Seconds (2));
    Config::Connect ("/NodeList/*/ApplicationList/*/$ns3::V4Ping/Rtt",
                     MakeCallback (&PingRtt));
}

bool CreateTables(DBAccess& db)
{
    bool bRet  = false;
    do
    {
        const char* createQuery1 = "CREATE TABLE IF NOT EXISTS SDNMasterTable (MeasurementID INTEGER PRIMARY KEY AUTOINCREMENT, MeasuremenRunTime INTEGER NOT NULL DEFAULT (NOW()),RTT REAL,Throughput REAL, Latency REAL,NoOfNodes INTEGER,NoOfSwitch INTEGER, NoOfController INTEGERNodeBufferingType CHAR(10),LinkCapacity REAL);";
        int iRet = db.ExecCommand(createQuery1);
        if (SQLITE_OK != iRet)
        {
            break;
        }
        const char* createQuery2 = "CREATE TABLE IF NOT EXISTS SDNStatTable (TimeInSec INTEGER, PacketSent REAL, PacketRevd REAL );";
        iRet = db.ExecCommand(createQuery2);
        if (SQLITE_OK != iRet)
        {
            break;
        }

        const char* createQuery3 = "CREATE TABLE IF NOT EXISTS SDNPacketTable (ID INTEGER, Size INTEGER , FlowDir INTEGER, DestIP INTEGER, SrcIP INTEGER, DestPort INTEGER, SrcPor INTEGER, L4Protocol CHAR(10),Payload BLOB  );";
        iRet = db.ExecCommand(createQuery3);
        if (SQLITE_OK != iRet)
        {
            break;
        }

        bRet = true;
    } while(0);
    return bRet;
}
int
main (int argc, char *argv[])
{
    bool bRet = CreateTables(gdb);
    if (false == bRet)
    {
        NS_LOG_INFO ("Database and table creation failed.");
        return 0;
    }
    else
    {
        NS_LOG_INFO ("Database and table success.");
    }

#ifdef NS3_OPENFLOW
    //
    // Allow the user to override any of the defaults and the above Bind() at
    // run-time, via command-line arguments
    //
    CommandLine cmd;
    cmd.AddValue ("v", "Verbose (turns on logging).", MakeCallback (&SetVerbose));
    cmd.AddValue ("verbose", "Verbose (turns on logging).", MakeCallback (&SetVerbose));
    cmd.AddValue ("d", "Use Drop Controller (Learning if not specified).", MakeCallback (&SetDrop));
    cmd.AddValue ("drop", "Use Drop Controller (Learning if not specified).", MakeCallback (&SetDrop));
    cmd.AddValue ("t", "Learning Controller Timeout (has no effect if drop controller is specified).", MakeCallback ( &SetTimeout));
    cmd.AddValue ("timeout", "Learning Controller Timeout (has no effect if drop controller is specified).", MakeCallback ( &SetTimeout));

    cmd.Parse (argc, argv);

    if (verbose)
    {
        LogComponentEnable ("OpenFlowCsmaSwitchExample", LOG_LEVEL_INFO);
        LogComponentEnable ("OpenFlowInterface", LOG_LEVEL_INFO);
        LogComponentEnable ("OpenFlowSwitchNetDevice", LOG_LEVEL_INFO);
    }

    //
    // Explicitly create the nodes required by the topology (shown above).
    //
    NS_LOG_INFO ("Create nodes.");
    NodeContainer terminals;
    terminals.Create (nTerminalCount);

    NodeContainer csmaSwitch;
    csmaSwitch.Create (nSwitchcount);

    NS_LOG_INFO ("Build Topology");
    CsmaHelper csma;

    //csma.SetChannelAttribute ("DataRate", DataRateValue (5000000));
    //csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2)));

    // Create the csma links, from each terminal to the switch
    NetDeviceContainer terminalDevices;
    NetDeviceContainer switchDevices;
    for (int i = 0; i < nTerminalCount ; i++)
    {
        NetDeviceContainer link = csma.Install (NodeContainer (terminals.Get (i), csmaSwitch));
        terminalDevices.Add (link.Get (0));
        switchDevices.Add (link.Get (1));
    }

    // Create the switch netdevice, which will do the packet switching
    Ptr<Node> switchNode = csmaSwitch.Get (0);
    OpenFlowSwitchHelper swtch;

    if (use_drop)
    {
        Ptr<ns3::ofi::DropController> controller = CreateObject<ns3::ofi::DropController> ();
        swtch.Install (switchNode, switchDevices, controller);
    }
    else
    {
        Ptr<ns3::ofi::LearningController> controller = CreateObject<ns3::ofi::LearningController> ();
        if (!timeout.IsZero ()) controller->SetAttribute ("ExpirationTime", TimeValue (timeout));
        swtch.Install (switchNode, switchDevices, controller);
    }

    // Add internet stack to the terminals
    InternetStackHelper internet;
    internet.Install (terminals);

    // We've got the "hardware" in place.  Now we need to add IP addresses.
    NS_LOG_INFO ("Assign IP Addresses.");
    Ipv4AddressHelper ipv4;
    ipv4.SetBase ("100.100.100.0", "255.255.255.0");
    ipv4.Assign (terminalDevices);

    // Create an OnOff application to send UDP datagrams from n0 to n1.
    NS_LOG_INFO ("Create Applications.");

    DetectRTT( terminals);

    DetectThrouthput( terminals);

    NS_LOG_INFO ("Run Simulation.");
    Simulator::Run ();
    Simulator::Destroy ();
    NS_LOG_INFO ("Done.");
#else
    NS_LOG_INFO ("NS-3 OpenFlow is not enabled. Cannot run simulation.");
#endif // NS3_OPENFLOW

}
